<template>
  <div class="container">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="80px">
      <el-form-item label="学科名称" prop="subjectName">
        <el-input
          v-model="ruleForm.subjectName"
          placeholder="请输入学科名"
        ></el-input>
      </el-form-item>
      <el-form-item label="是否显示" prop="isFrontDisplay">
        <el-switch
          v-model="delivery"
          active-color="#13ce66"
          inactive-color="#ff4949"
        >
        </el-switch>
      </el-form-item>
      <el-form-item style="float: right; padding-top: 20px">
        <el-button @click="succeed()">取 消</el-button>
        <el-button type="primary" @click="submitForm(isEdit)">确 定</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { add, detail, update } from '@/api/hmmm/subjects'
export default {
  props: {
    isEdit: {
      type: Boolean,
      required: true
    },
    id: {
      type: Number,
      default: null
    }
  },
  data () {
    return {
      ruleForm: {
        subjectName: '',
        isFrontDisplay: 0
      },
      rules: {
        subjectName: [
          { required: true, message: '请输入学科名', trigger: 'blur' }
        ]
      },
      delivery: true
    }
  },
  async created () {
    // console.log('this.id', this.id)
    if (this.isEdit) {
      const { data: res } = await detail({ id: this.id })
      // console.log(res)
      this.ruleForm = res
    }
  },
  methods: {
    submitForm () {
      // 兜底校验
      this.$refs.ruleForm.validate((reslut) => {
        // console.log('reslut', reslut)
        if (!reslut) return
        if (this.delivery) {
          this.ruleForm.isFrontDisplay = 1
        } else {
          this.ruleForm.isFrontDisplay = 0
        }
        if (!this.isEdit) {
          this.addSub()
        } else {
          this.delSub()
        }
      })
    },
    addSub () {
      // console.log('this.ruleForm.isFrontDisplay', this.ruleForm.isFrontDisplay)
      add(this.ruleForm)
        .then((response) => {
          // console.log('1234', response)
          this.$message.success('新增学科成功!')
          this.succeed()
        })
        .catch((response) => {
          this.$message.error('新增失败!')
        })
      // this.$message.info('已取消操作!')
    },
    delSub () {
      update(this.ruleForm)
        .then((response) => {
          // console.log('1234', response)
          this.$message.success('修改学科成功!')
          this.succeed()
        })
        .catch((response) => {
          this.$message.error('修改失败!')
        })
    },
    succeed () {
      this.ruleForm = {
        subjectName: '',
        isFrontDisplay: 0
      }
      this.$emit('success')
    }
  }
}
</script>

<style scoped lang="scss">
.container {
  height: 160px;
}
</style>
